import { getAddress } from '../../utils/userLocation';
import { showAuthSet, openAuthsetting } from '../../utils/userAuth';
const app = getApp();
const requests = require('../../config/request')
var util = require('./../../utils/util.js');
var api = require('./../../config/api.js');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        isLocation: true, // 是否定位
        cityName: '', // 当前城市
        fast: ['帮我送', '帮我取', '帮我买', '帮排队', '帮我办'],
        fastIndex: 0,
        tabBoxWidth: 0, // tab元素的宽度
        tabBlockVal: 19, // tab底部滑块left值
        contentLeftVal: 0, // tab下的内容left值
        tabScrollWidth: 375, // tab-scroll元素的宽度

        userInfo: {},
        hasUserInfo: false,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        canIUseGetUserProfile: false,
        schoolName: '',
        banners: [],
        autoplay: true,
        shopLists: [],
        menus: [],
        loadTimeInterval: true,
        page: 1,
        pageEnd: false,
        tableIndex: 0,
        commentList: [],
        commentPage: 1,
        canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
        commentContent: '',
        commentPid: 0,
        showInput: false,
        commentEnd: false,
        isClearComment: false,
        isRefresh: false,
    },

    // 选择城市
    selectCity: function () {
        app.go('/pages/cityList/cityList');
    },
    // 快速处理
    fnFastHandleSwitch: function (e) {
        let { index } = e.currentTarget.dataset;
        if (index === this.data.fastIndex) {
            return;
        }
        // console.log(index)
        switch (index) {
            case 0:
            case 1:
                this.setData({ fastIndex: index });
                this.fnTabBottomBlockMove(index);
				app.set('__tab__index', index);
                break;
            case 2:
                console.log(this.data.fast[index]); break;
            case 3:
                console.log(this.data.fast[index]); break;
            case 4:
                console.log(this.data.fast[index]); break;
        }

    },
    // tab点击
    fnTabBottomBlockMove: function (index) {

        const { tabBoxWidth, fast, tabScrollWidth } = this.data;

        // tab底部滑块移动
        let itemWidth = tabBoxWidth / fast.length;
        let tabBlockVal = itemWidth * index + 19;

        // 获取内容元素
        let contentLeftVal = tabScrollWidth * index;
        // console.log('contentLeftVal', contentLeftVal)
        this.setData({ tabBlockVal, contentLeftVal });
    },

    // 获取tab盒子的宽度
    fnGetTabBoxWidth: function () {
        let _that = this;
        let query = wx.createSelectorQuery();
        query.select('.fh-tab').boundingClientRect(function (rect) {
            _that.setData({ tabBoxWidth: rect.width });
        }).exec();
    },

    // 获取tab-scroll元素的宽度
    fnGetTabScrollWidth: function () {
        let _that = this;
        let query = wx.createSelectorQuery();
        query.select('.tab-scroll').boundingClientRect(function (rect) {
            _that.setData({ tabScrollWidth: rect.width });
        }).exec();

    },

    // 第二个板块下item点击
    fnOptionClick: function (e) {
        let { page } = e.currentTarget.dataset;
        console.log('第二个板块-page--->', page);
    },

    // 获取定位和当前城市信息
    fnGetLocation: function () {
        let _that = this;
        getAddress().then(function (data) {
            _that.setData({ cityName: data.address_component.city, isLocation: true });
            // 将定位信息存至缓存
            app.set('__user__address', data);
        }, function (error) {
            console.log(error)
            _that.setData({ isLocation: false });
        });
    },

    // 查看用户是否定位授权 
    fnShowUserIsLocationAuth: function () {
        let _that = this;
        showAuthSet().then(function (data) {
            // console.log('data', data)
            if (!data['scope.userLocation']) { // 未授权
                app.modal('提示', '未开启定位，是否前往设置？').then(function (set) {
                    // console.log('set', set)
                    if (set.confirm) { // 点击确认
                        openAuthsetting().then(function (res) { // 打开授权设置页面
                            // console.log('scope.userLocation', data['scope.userLocation'])
                            if (res['scope.userLocation']) { // 已开定位权限
                                _that.fnGetLocation();
                            } else {
                                app.toast('未打开定位权限');
                            }
                        })
                    }
                });

            }
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.fnGetLocation();
        this.fnGetTabBoxWidth();
        this.fnGetTabScrollWidth();

        if (wx.getUserProfile) {
          this.setData({
            canIUseGetUserProfile: true
          })
        }
    
        // var commentList = this.getCommentStorge()
        // this.setData({commentList: commentList})
        // if (commentList.length > 0){
        //   this.setData({isClearComment: true})
        // }
    
        let index = setInterval(() => {
          if (app.globalData.schoolInfo && app.globalData.schoolInfo.csName !== undefined) {
            clearInterval(index);
            this.setData({
              schoolName: app.globalData.schoolInfo.csName
            });
    
            // this.getCommentList(true)
            return;
          }
        }, 100)
        // this.getBannerMenu();
        // this.popularShopList();
    },

    getUserProfile(e) {
      // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
      wx.getUserProfile({
        desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    },
    getBannerMenu() {
      requests.homeMenuApi().then(({
        list,
        menu
      }) => {
        Array.isArray(list) && this.setData({
          banners: list
        })
  
        Array.isArray(menu) && this.setData({
          menus: menu
        })
  
      })
    },
    popularShopList() { // 热门店铺
      console.log('page:'+ this.data.page)
      requests.shopList({
        search_key: '',
        is_hot: '',
        cate_id2: '',
        page: this.data.page
      }).then(({
        list
      }) => {
        var newList = this.data.shopLists.concat(list);
        if (list.length < 20){
          console.log(list.length)
          this.setData({pageEnd: true});
        }
        Array.isArray(list) && this.setData({
          shopLists: newList
        })
      })
    },
  
    redirectToSearch() {
      wx.navigateTo({
        url: '../shop/list/index',
      })
    },
  
    redirectToShop(e) {
      let shopId = e.currentTarget.dataset.shopId;
      wx.navigateTo({
        url: '../shop/shop?shop_id=' + shopId,
      })
    },
    getUserInfo(e) {
      // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
      this.setData({
        userInfo: e.detail.userInfo,
        hasUserInfo: true
      })
    },
    
    clickMenu(e) {
      let category = e.currentTarget.dataset.category;
      if (!category) {
        return;
      }
  
      wx.navigateTo({
        url: '../shop/list/index?category=' + category,
      })
    },
  
    changeTab(e){
      let index = e.currentTarget.dataset.index;
      this.setData({tableIndex: index})
    },
  
    toPost(){
      wx.navigateTo({
        url: '../post/post'
      })
    },
  
    bindReplaceInput(e){
      this.setData({commentContent: e.detail.value});
    },
  
    showInput(e){
      this.setData({commentPid:  e.currentTarget.dataset.id})
      this.setData({showInput: true})
    },
  
    inputBlur(e){
      this.setData({showInput: false})
    },
  
    previewImg(e){
      for (var i=0;i<this.data.commentList.length;i++){
        if (this.data.commentList[i].cId == e.currentTarget.dataset.id){
          wx.previewImage({
            current: e.currentTarget.dataset.url, // 当前显示图片的http链接
            urls: this.data.commentList[i].picList // 需要预览的图片http链接列表
          })
        }
      }
  
      wx.previewImage({
        current: '', // 当前显示图片的http链接
        urls: [] // 需要预览的图片http链接列表
      })
    },
  
    sendComment(){
      var that = this;
      var postData = {};
      postData.token = app.globalData.userInfo.token;
      postData.cPid = this.data.commentPid;
      postData.cContent = this.data.commentContent;
      postData.pgId = 0
      util.myRequest(api.AddComment, postData, function(data){
        // that.getCommentList()
        var newCommentList = that.data.commentList;
        for (var i=0;i<newCommentList.length;i++){
          if (newCommentList[i].cId == that.data.commentPid){
              var replyInfo = {}
              replyInfo.cContent = that.data.commentContent
              replyInfo.userInfo = {uName: app.globalData.userInfo.uName}
              newCommentList[i].replyList.push(replyInfo)
              that.setData({commentList: newCommentList, commentContent: ''});
              console.log(newCommentList)
          }
        }
      });
    },
  
    atCommentBottom: function(){
      console.log('dddddddddddddd')
      console.log(this.data.commentEnd)
      console.log(this.data.loadTimeInterval)
      var that = this;
      if (this.data.commentEnd){
        return
      }
      if (this.data.loadTimeInterval){
        that.setData({loadTimeInterval: false});
  
        that.setData({commentPage: that.data.commentPage + 1})
        that.getCommentList(false)
  
  
        setTimeout(function(){
          that.setData({loadTimeInterval: true});
        }, 1500);
      }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        if (!this.data.isLocation) {
            this.fnShowUserIsLocationAuth();
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
      return app.globalData.shareInfo;
    }
})